package com.tanhua.admin.listeners;

import com.alibaba.fastjson.JSON;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.db.Log;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class LogListener {

    @Autowired
    private LogMapper logMapper;

    /**
     * 方法：自动获取消息，在方法内容使用消息完成业务逻辑
     * 要求：
     *    没有返回值，有参数（和消息的类型一致：String）
     * 配置：
     *    在方法上通过注解配置（@RabbitListener）
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(
                            value = "tanhua.log.queue"
                    ),
                    exchange = @Exchange(
                            value = "tanhua.log.exchange",
                            type = ExchangeTypes.TOPIC
                    ),
                    key = "log.*"
            )
    )
    public void log(String message) {
        System.out.println("message="+message);
        //1、将JSON字符串还原成Map对象
        Map map = JSON.parseObject(message, Map.class);//将JSON字符串，转化成java对象
        //2、获取传递的消息数据
        String type = map.get("type").toString();
        String logTime = map.get("logTime").toString();
        String string = map.get("userId").toString();
        Long userId = Long.valueOf(string);
        //3、构造Log对象
        Log log = new Log();
        log.setUserId(userId);
        log.setType(type);
        log.setLogTime(logTime);
        //4、保存
        logMapper.insert(log);
    }
}
